package han.cirno.corrupt.util

import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.InputStream
import java.io.ObjectInputStream
import java.io.ObjectOutputStream
import java.io.OutputStream
import kotlin.reflect.KClass

object SerialUtil {
    inline fun <reified T:Any> deserialize(inputStream: InputStream?): T? {
        try {
            ObjectInputStream(inputStream).use { objectInputStream ->
                val o: Any = objectInputStream.readObject() ?: return null
                if(o !is T)return null
                return o
            }
        } catch (e: Exception) {
            return null
        }
    }

    inline fun <reified T:Any> deserialize(bytes: ByteArray?, tClass: KClass<T>): T? {
        try {
            ByteArrayInputStream(bytes).use { byteArrayInputStream ->
                return deserialize(byteArrayInputStream)
            }
        } catch (e: Exception) {
            return null
        }
    }

    inline fun <reified T:Any> deserialize(file: File?, tClass: KClass<T>): T? {
        try {
            FileInputStream(file).use { fileInputStream ->
                return deserialize(fileInputStream)
            }
        } catch (e: Exception) {
            return null
        }
    }

    inline fun <reified T:Any> serialize(outputStream: OutputStream, t: T) {
        ObjectOutputStream(outputStream).use { it.writeObject(t) }
    }

    inline fun <reified T:Any> serialize(file: File, t: T){
        FileOutputStream(file).use { serialize(it,t) }
    }

    inline fun <reified T:Any> serialize(t:T):ByteArray{
        return ByteArrayOutputStream().use {
            serialize(it,t)
            it
        }.toByteArray()
    }
}
